﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Hisun.Models;

namespace Hisun.View.SCRB
{
    public partial class Scrb_Daily_Reload : System.Web.UI.Page
    {
        private string mypipID;
        int mycostcenterID;
        DateTime dt_myday;
        public string alter;

        HisunDBDataContext db = new HisunDBDataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            mypipID = HttpUtility.UrlDecode(Request.QueryString["mypip"]);
            dt_myday = DateTime.Parse(HttpUtility.UrlDecode(Request.QueryString["myday"]));
            bindmypip();

            if (!IsPostBack)
            {

                BindEmptyData();
            }
        }

        /// <summary>
        /// 获取当前会计期间
        /// </summary>
        /// <param name="it_date"></param>
        /// <returns></returns>
        private string getAccoutperiod(DateTime it_date)
        {

            var kjqk = (from a in db.TABC_JS_AccountPeriod
                        where a.成本开始日期 <= it_date
                               && a.成本结账日期 >= it_date
                        select a.会计期间ID).Single();

            return kjqk;
        }
        private string getAccoutperiod()
        {
            return getAccoutperiod(this.dt_myday);
        }

        private void bindmypip()
        {
            var mypip = (from a in db.TABC_JS_ProductInProcess
                         where a.中间体ID == mypipID
                         select a).Single();


            mycostcenterID = (int)mypip.作业中心ID;
            string mycostcentername = (from a in db.TABC_JS_CostCenter
                                       where a.作业中心ID == mycostcenterID
                                       select a.作业中心名称).Single();

            Label_CostCenter.Text = mycostcentername;
            Label_PIPNAME.Text = mypip.中间体名称;
            Label_myday.Text = dt_myday.ToShortDateString();



        }

        private string splitbatch(string batch)
        {
            if (batch.IndexOf('/') > 0)
            {
                batch = batch.Split('/')[1];
            }

            return batch;
        }

        private string joinbatch(string batch)
        {
            if (batch.IndexOf('/') > 0)
            {
                return batch;
            }
            return this.mypipID + "/" + batch;

        }

        

        protected void BindEmptyData()
        {
            
            //    var qs = from a in db.TSCRB_JS_BatchInfo
            //             join c in db.TSCRB_DM_BatchStatus on
            //             a.批号类型 equals c.DM
            //             join d in
            //                 (from b in db.TSCRB_JS_BatchInfoDetail
            //                  where b.投入日期 == dt_myday || b.中止日期 == dt_myday
            //                  select b)
            //             on a.批号 equals d.批号 into m
            //             from x in m.DefaultIfEmpty()
            //             join y in db.TSCRB_JS_BatchInfo on
            //             x.原批号 equals y.批号
            //             where a.中间体ID == mypipID && (a.批号类型 == "P" || a.批号类型 == "R")
            //             select new
            //             {
            //                 ID = (x == null ? 0 : x.ID),
            //                 批号 = (x.原批号 == null ? a.批号 : x.原批号),
            //                 新批号 = (x.原批号 == null ? "" : a.批号),
            //                 是否重投 = (a.批号类型 == "R"),
            //                 折批系数 = (y == null ? 1 : y.折批系数)

            //             };

            //DataTable dt1 = new DataTable();
            //dt1.Columns.Add("ID");
            //dt1.Columns.Add("是否重投", typeof(bool));
            //dt1.Columns.Add("批号");
            //dt1.Columns.Add("新批号");
            //dt1.Columns.Add("折批系数");
            //dt1.Columns.Add("状态"); 
                var qs = (from a in db.TSCRB_JS_BatchInfo
                          join b in db.TSCRB_DM_BatchStatus on
                          a.批号类型 equals b.DM
                          join c in db.TSCRB_JS_BatchInfo on
                          a.原批号 equals c.批号
                          join d in db.TSCRB_JS_BatchInfoDetail on
                          a.批号 equals d.批号
                          where a.批号类型 == "R" 
                          && a.中间体ID == mypipID
                          && a.原批号 != null 
                          && d.投入日期 == dt_myday  
                          && d.中止日期 ==null
                          select new
                          {

                              ID = d.ID,
                              是否重投 = (a.批号类型 == "R"),
                              批号 =  a.原批号,
                              新批号 = a.批号,
                              折批系数 =  a.折批系数==null ? 1.0 :a.折批系数.Value,
                              b.状态
                          }).Concat(
                                      from a in db.TSCRB_JS_BatchInfo
                                      join b in db.TSCRB_DM_BatchStatus on
                                      a.批号类型 equals b.DM
                                      join c in db.TSCRB_JS_BatchInfoDetail on
                                      a.批号 equals c.批号
                                      where a.批号类型 == "P" 
                                      && c.中止日期 < dt_myday
                                      && a.中间体ID == mypipID
                                       
                                      select new
                                      {
                                          ID = (long)0,
                                          是否重投 = (a.批号类型 == "R"),
                                          批号 =  a.批号,
                                          新批号 = "",
                                          折批系数 = 1.0,
                                          b.状态
                                      }
                         ).Concat(from a in db.TSCRB_JS_BatchInfo
                                  join b in db.TSCRB_DM_BatchStatus on
                                  a.批号类型 equals b.DM
                                  join d in db.TSCRB_JS_BatchInfoDetail on
                                  a.批号 equals d.批号
                                  where a.中间体ID == mypipID 
                                  && a.批号类型 == "R" 
                                  && a.原批号 == null 
                                  && d.投入日期 == dt_myday 
                                  && d.中止日期 == null
                                  select new
                                  {

                                      ID = d.ID,
                                      是否重投 = (a.批号类型 == "R"),
                                      批号 = a.批号,
                                      新批号 = " ",
                                      折批系数 = a.折批系数 == null ? 1.0 : a.折批系数.Value,
                                      b.状态
                                  }

                );
            
            GridView1.DataSource = qs;

            GridView1.DataBind();
        }
        protected DataTable GetDataFromGrid()
        {

            DataTable dt1 = new DataTable();
            dt1.Columns.Add("ID");
            dt1.Columns.Add("是否重投");
            dt1.Columns.Add("批号");
            dt1.Columns.Add("新批号");
            dt1.Columns.Add("折批系数");
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                GridViewRow gRow = GridView1.Rows[i];
                DataRow newRow = dt1.NewRow();
                newRow[0] = GridView1.DataKeys[i].Value;
                newRow[1] = ((CheckBox)gRow.FindControl("CheckBox1")).Checked;
                newRow[2] = ((TextBox)gRow.FindControl("TextBox1")).Text;
                newRow[3] = ((TextBox)gRow.FindControl("TextBox2")).Text; 
                newRow[4] = ((TextBox)gRow.FindControl("TextBox3")).Text;
                dt1.Rows.Add(newRow);
            }
            dt1.AcceptChanges();
            return dt1;
        }


        private bool checkbachexist(string batchnumber)
        {
            if (batchnumber.IndexOf('/') < 0)
            {
                batchnumber = joinbatch(batchnumber);
            }
            var q = from a in db.TSCRB_JS_BatchInfo
                    where
                        a.批号 == batchnumber
                    select a;
            if (q.Count() > 0)
            {
                return true;
            }
            return false;

        }

        private void UpdateTransRate(string Batch)
        {
            double sumrate = (from a in db.TSCRB_JS_Out
                              where a.批号 == Batch
                              select a.转出系数).Sum().Value;

            var q = (from a in db.TSCRB_JS_BatchInfo where a.批号 == Batch select a).Single();
            q.转出率 = sumrate;
            db.SubmitChanges();
        }
        protected void Button_Save_Click(object sender, EventArgs e)
        {
            DataTable dt1 = GetDataFromGrid(); 
            string 批号="";
            string 新批号 ="";
            try
            {
                foreach (DataRow row in dt1.Rows)
                {
                    新批号 = 批号 = "";
                    批号 = joinbatch(row["批号"].ToString());
                    新批号 = joinbatch(row["新批号"].ToString());

                    if (row["ID"].ToString() != "0") //说明已经有数据
                    {


                        var updatedetail = (from a in db.TSCRB_JS_BatchInfoDetail
                                            where a.ID == long.Parse(row["ID"].ToString())
                                            select a).Single();
                        var update = (from a in db.TSCRB_JS_BatchInfo
                                      where a.批号 == updatedetail.批号
                                      select a).Single();

                        if (row["是否重投"].ToString() == "True") //的确重投了
                        {
                            update.折批系数 = float.Parse(row["折批系数"].ToString());

                            if (updatedetail.批号 == 新批号)
                            {

                            }
                            else if (updatedetail.批号 == 批号)
                            {

                                if (row["新批号"].ToString().Length > 1)
                                {


                                    var Batchinfo = (from a in db.TSCRB_JS_BatchInfo
                                                     where a.批号 == 批号
                                                     select a).Single();
                                    Batchinfo.批号类型 = "Z"; //重投结束
                                    Batchinfo.结束日期 = dt_myday;

                                    TSCRB_JS_BatchInfo newBatchInfo = new TSCRB_JS_BatchInfo();
                                    newBatchInfo.会计期间ID = getAccoutperiod();
                                    newBatchInfo.批号 = 新批号;
                                    newBatchInfo.批号类型 = "R";
                                    newBatchInfo.中间体ID = mypipID;
                                    newBatchInfo.折批系数 = float.Parse(row["折批系数"].ToString());
                                    newBatchInfo.原批号 = 批号;
                                    db.TSCRB_JS_BatchInfo.InsertOnSubmit(newBatchInfo);

                                    TSCRB_JS_BatchInfoDetail insert = new TSCRB_JS_BatchInfoDetail();
                                    insert.会计期间ID = getAccoutperiod();
                                    insert.批号 = 新批号;
                                    insert.投入日期 = dt_myday;
                                    insert.中间体ID = mypipID;
                                    insert.原批号 = 批号;

                                    db.TSCRB_JS_BatchInfoDetail.InsertOnSubmit(insert);
                                }

                            }
                            else
                            {
                                if (row["新批号"].ToString().Length > 1)
                                {

                                    if (!checkbachexist(新批号))
                                    {
                                        update.批号 = 新批号;
                                        update.原批号 = 批号;
                                        updatedetail.批号 = 新批号;
                                        updatedetail.原批号 = 批号;
                                    }
                                }
                            }


                        }
                        else //把重投勾去掉了
                        {
                            if (update.原批号 != null)
                            {
                                var q = (from a in db.TSCRB_JS_BatchInfo
                                         where a.批号 == update.原批号
                                         select a).Single();
                                q.批号类型 = "P"; //修改为中止
                                db.TSCRB_JS_BatchInfo.DeleteOnSubmit(update); //删除批号

                            }
                            else
                            {
                                update.批号类型 = "P";
                            }

                            db.TSCRB_JS_BatchInfoDetail.DeleteOnSubmit(updatedetail);



                        }


                        db.SubmitChanges();


                    }
                    else // out id is null ,   insert a line into  out table
                    {
                        if (row["是否重投"].ToString() == "True")
                        {
                            TSCRB_JS_BatchInfoDetail insert = new TSCRB_JS_BatchInfoDetail();


                            if (splitbatch(新批号) == "" || 新批号 == 批号)//没有建立新批号
                            {
                                var Batchinfo = (from a in db.TSCRB_JS_BatchInfo
                                                 where a.批号 == 批号
                                                 select a).Single();
                                Batchinfo.批号类型 = "R";

                                insert.会计期间ID = getAccoutperiod();
                                insert.投入日期 = dt_myday;
                                insert.批号 = 批号;
                                insert.中间体ID = mypipID;


                            }
                            else //新批号
                            {
                                if (checkbachexist(新批号))
                                {
                                    Label_alter.Text += splitbatch(新批号) + "已存在";
                                    continue;
                                }

                                //新批号=joinbatch(新批号);
                                var Batchinfo = (from a in db.TSCRB_JS_BatchInfo
                                                 where a.批号 == 批号
                                                 select a).Single();
                                Batchinfo.批号类型 = "Z"; //重投结束
                                Batchinfo.结束日期 = dt_myday;

                                TSCRB_JS_BatchInfo newBatchInfo = new TSCRB_JS_BatchInfo();
                                newBatchInfo.会计期间ID = getAccoutperiod();
                                newBatchInfo.批号 = 新批号;
                                newBatchInfo.批号类型 = "R";
                                newBatchInfo.中间体ID = mypipID;
                                newBatchInfo.折批系数 = float.Parse(row["折批系数"].ToString());
                                newBatchInfo.原批号 = 批号;
                                db.TSCRB_JS_BatchInfo.InsertOnSubmit(newBatchInfo);


                                insert.会计期间ID = getAccoutperiod();
                                insert.批号 = 新批号;
                                insert.投入日期 = dt_myday;
                                insert.中间体ID = mypipID;
                                insert.原批号 = 批号;


                            }

                            db.TSCRB_JS_BatchInfoDetail.InsertOnSubmit(insert);

                        }
                        db.SubmitChanges();
                    }





                }

 
            //    Label_alter.Text += "保存成功";

                alter = "<script>alert('保存成功');</script>";

                BindEmptyData();
            }
            catch
            {
                alter = "<script>alert('保存失败');</script>";
            }
           
            BindEmptyData();

        }

        protected void Button_Back_Click(object sender, EventArgs e)
        {
            Response.Redirect("Scrb_Daily_MainPage.aspx?centerid=" + mycostcenterID.ToString() + "&PIPid=" + mypipID);
      
        }


 
    }
}
